<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Welcome to Design Zone......</title>
        <link rel="stylesheet" type="text/css" href="scripts/ext/resources/css/ext-all.css" />
        <link rel="stylesheet" type="text/css" href="styles/dzbase.css" />
		<link rel="stylesheet" type="text/css" href="styles/summary.css" />
        <script type="text/javascript" src="scripts/ext/adapter/ext-base.js">
        </script>
        <script type="text/javascript" src="scripts/ext/ext-all.js">
        </script>
		<script type="text/javascript" src="scripts/ext/GroupSummary.js"></script>
        <script type="text/javascript" src="scripts/utils.js">
        </script>
        <script type="text/javascript" src="scripts/i18nMessage.js">
        </script>
        <script type="text/javascript">
            //For calculate item price
			var quantity;
            var unitPirce;
			var q1;
			var c1;
			var q2;
			var c2;
			var q3;
			var c3;
			var q4;
			var c4;
			var q5;
			var c5;
			var otherCo;
            
            var technicChartId;
            var yarnId;
            
			var orderItemForm;
            var orderItemStore;
            var orderItemGrid;
            
            var technicChartXmlLoader = new xmlLoader('TechnicChartServlet?action=5');
            var technicChartStore = new Ext.data.Store({
                reader: new Ext.data.XmlReader({
                    record: 'item',
                    id: 'id',
                    totalRecords: 'itemTotal'
                }, ['id', 'reference', 'weight', 'comment', 'photoName', 'comment', 'diffCoefficient', 'needle', 'cotation']),
                data: technicChartXmlLoader.getXml()
            });
            
            var technicChartCombo = new Ext.form.ComboBox({
                fieldLabel: 'Technic chart',
                name: 'technicChartId',
				id: 'technicChartId',
                store: technicChartStore,
                displayField: 'reference',
                valueField: 'id',
                tpl: '<tpl for="."><div ext:qtip="<b>Weight(kg)</b>:&nbsp;&nbsp;{weight}<br/>' +
                '<b>Needle:</b>&nbsp;&nbsp;{needle}<br/>' +
                '<b>Cotation:</b>&nbsp;&nbsp;{cotation}<br/>' +
                '<b>Difficulty coefficient:</b>&nbsp;&nbsp;{diffCoefficient}<br/>' +
                '<b>Comment:</b>&nbsp;&nbsp;{comment}<br/>' +
                '" class="x-combo-list-item">{reference}</div></tpl>',
                typeAhead: true,
                mode: 'local',
                forceSelection: true,
                triggerAction: 'all',
                emptyText: 'Select a technic chart...',
                selectOnFocus: true,
                allowBlank: false,
                blankText: 'This fieled must be filled out.'
            });
            
            technicChartCombo.on('select', function(combo, record, index){
                document.getElementById('photo').src = "_temp/" + record.data.photoName;
                technicChartId = record.data.id;
				yarnStore.load({
                    params: {
                        id: technicChartId
                    }
                });
            });
            
            //var yarnXmlLoader = new xmlLoader('YarnServlet?action=5');
            var yarnStore = new Ext.data.Store({
				url: 'YarnServlet?action=6',
                reader: new Ext.data.XmlReader({
                    record: 'item',
                    id: 'id',
                    totalRecords: 'itemTotal'
                }, ['id', 'yarnName','unitPrice', 'q1', 'c1', 'q2', 'c2', 'q3', 'c3', 'q4', 'c4', 'q5', 'c5', 'otherCo']),
               // data: yarnXmlLoader.getXml()
			   remoteSort: true
            });
            
            var yarnCombo = new Ext.form.ComboBox({
                fieldLabel: 'Yarn',
                name: 'yarnId',
				id:'yarnId',
                store: yarnStore,
                displayField: 'yarnName',
                valueField: 'id',
                tpl: '<tpl for="."><div ext:qtip="<b>Unit price:</b>&nbsp;&nbsp;{unitPrice}<br/>' +
                'Quantity<b>&nbsp;<=&nbsp;</b>&nbsp;&nbsp;{q1}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>&nbsp;X&nbsp;</b>&nbsp;&nbsp;{c1}<br/>' +
				'&nbsp;&nbsp;{q1}&nbsp;&nbsp;<b>&nbsp;<&nbsp;</b>Quantity<b>&nbsp;<=&nbsp;</b>{q2}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>&nbsp;X&nbsp;</b>&nbsp;&nbsp;{c2}<br/>' +
				'&nbsp;&nbsp;{q2}&nbsp;&nbsp;<b>&nbsp;<&nbsp;</b>Quantity<b>&nbsp;<=&nbsp;</b>{q3}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>&nbsp;X&nbsp;</b>&nbsp;&nbsp;{c3}<br/>' +
				'&nbsp;&nbsp;{q3}&nbsp;&nbsp;<b>&nbsp;<&nbsp;</b>Quantity<b>&nbsp;<=&nbsp;</b>{q4}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>&nbsp;X&nbsp;</b>&nbsp;&nbsp;{c4}<br/>' +
				'&nbsp;&nbsp;{q4}&nbsp;&nbsp;<b>&nbsp;<&nbsp;</b>Quantity<b>&nbsp;<=&nbsp;</b>{q5}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>&nbsp;X&nbsp;</b>&nbsp;&nbsp;{c5}<br/>' +
				'<b>Other coefficient:</b>&nbsp;&nbsp;{otherCo}<br/>' +
                '" class="x-combo-list-item">{yarnName}</div></tpl>',
                typeAhead: true,
                mode: 'local',
                forceSelection: true,
                triggerAction: 'all',
                emptyText: 'Select a yarn...',
                selectOnFocus: true,
                allowBlank: false,
                blankText: 'This fieled must be filled out.'
            });
            
            yarnCombo.on('select', function(combo, record, index){
                document.getElementById('unitPrice').value = record.data.unitPrice;
				q1 = record.data.q1;
				c1 = record.data.c1;
				q2 = record.data.q2;
				c2 = record.data.c2;
				q3 = record.data.q3;
				c3 = record.data.c3;
				q4 = record.data.q4;
				c4 = record.data.c4;
				q5 = record.data.q5;
				c5 = record.data.c5;
				otherCo = record.data.otherCo;
				document.getElementById('tcmId').value =  record.data.id;
            });
            
            var colorXmlLoader = new xmlLoader('ColorServlet?action=5');
            var colorStore = new Ext.data.Store({
                reader: new Ext.data.XmlReader({
                    record: 'item',
                    id: 'id',
                    totalRecords: 'itemTotal'
                }, ['id', 'number']),
                data: colorXmlLoader.getXml()
            });
            
            var colorCombo = new Ext.form.ComboBox({
                fieldLabel: 'Color',
                name: 'color',
                store: colorStore,
                displayField: 'number',
                typeAhead: true,
                mode: 'local',
                forceSelection: true,
                triggerAction: 'all',
                emptyText: 'Select a color...',
                selectOnFocus: true,
                allowBlank: false,
                blankText: 'This fieled must be filled out.'
            });
            
            var orderId = getPrarmeterValue(window.location, 'orderId');
            var orderXMLReader = new Ext.data.XmlReader({
                record: 'item'
            }, [{
                name: 'id',
                mapping: 'id'
            }, {
                name: 'customerName',
                mapping: 'customerName'
            }, {
                name: 'customerLinkman',
                mapping: 'customerLinkman'
            }, {
                name: 'customerAddress',
                mapping: 'customerAddress'
            }, {
                name: 'isPrinted',
                mapping: 'isPrinted'
            }, {
                name: 'isConfirmed',
                mapping: 'isConfirmed'
            }, {
                name: 'customerComment',
                mapping: 'customerComment'
            }, {
                name: 'customerEmail',
                mapping: 'customerEmail'
            }, {
                name: 'customerTel',
                mapping: 'customerTel'
            }, {
                name: 'customerMb',
                mapping: 'customerMb'
            }, {
                name: 'payment1',
                mapping: 'payment1'
            },{
                name: 'payment2',
                mapping: 'payment2'
            },{
                name: 'totalPrice',
                mapping: 'totalPrice'
            }]);
            
            var xmlLoader = new xmlLoader('OrderServlet?action=3&id=' + orderId);
            
            var orderRecord = orderXMLReader.readRecords(xmlLoader.getXml()).records[0];
            var itemTplMarkup = ['<table cellspacing="0" id="the-table" style="width: 100%;"><tbody>', 
			'<tr><td style="background:#eeeeee;" colspan="6">Customer information</td><td rowspan="5" width="250"><img id="photo" height="180" src="_temp/noimage.gif"/></td></tr>', 
			'<tr><td style="background:#eeeeee;width: 15%;">', 'Customer name', 
			'</td><td>{customerName}</td>', '<td style="background:#eeeeee;width: 15%;">', 
			'Contant man', '</td><td>{customerLinkman}</td>', '<td style="background:#eeeeee;">', 'Tel', '</td><td>{customerTel}</td></tr>', 
			'<tr><td style="background:#eeeeee;">', 'Mobile', '</td><td>{customerMb}</td>', '<td style="background:#eeeeee;">', 'Email', '</td><td>{customerEmail}</td>',
			 '<td style="background:#eeeeee;">', 'Address', '</td><td>{customerAddress}</td></tr>', 
			 '<tr><td style="background:#eeeeee;">', 
			 '30% at order to confirm', '</td><td>{payment1:usMoney}</td><td style="background:#eeeeee;">', '70% 10 days before departure', 
			 '</td><td>{payment2:usMoney}</td><td style="background:#eeeeee;">', 'Total price', '</td><td>{totalPrice:usMoney}</td></tr>',
			 '<tr><td style="background:#eeeeee;">', 'Comment', '</td><td colspan="5">{customerComment}</td></tr>',
			 '</tbody></table>'];
            var itemTpl = new Ext.Template(itemTplMarkup);
            
            var deleteCallback = function(btn){
                if (btn == 'yes') {
                    Ext.Ajax.request({
                        url: 'OrderServlet?action=17&id=' + deleteId,
                        success: function(o){
                            if (o.responseText == 'success') {
                                 messageTip.msg('Tip', 'Delete item successfully');
								  window.setTimeout(function(){
											window.location.reload();
									}, '700');                            }
                            else {
                               messageTip.msg('Tip', 'Delete item unsuccessfully');
                            }
                        },
                        failure: function(o){
                            messageTip.msg('Tip', 'Delete item failed');
                        },
                        params: {
                            foo: 'bar'
                        }
                    });
                }
            }
            
            var editCallback = function(){
                orderItemForm.getForm().load({
                    url: 'OrderServlet?action=16&id=' + editId,
                    waitMsg: Ext.LoadMask.prototype.msg,
                    success: function(form, action){
                    	document.getElementById('photo').src = "_temp/" + document.getElementById('photoName').value;
						q1 = document.getElementById('q1').value;
						c1 = document.getElementById('c1').value;
						
						q2 = document.getElementById('q2').value;
						c2 = document.getElementById('c2').value;
						
						q3 = document.getElementById('q3').value;
						c3 = document.getElementById('c3').value;
						
						q4 = document.getElementById('q4').value;
						c4 = document.getElementById('c4').value;
						
						q5 = document.getElementById('q5').value;
						c5 = document.getElementById('c5').value;
						
						yarnStore.load({
		                    params: {
		                        id: technicChartCombo.getValue()
		                    }
		                });
						
                    }
                });
            }
            
            Ext.onReady(function(){
                Ext.QuickTips.init();
                Ext.form.Field.prototype.msgTarget = 'side';
                
                itemTpl.append('order', orderRecord.data);
                
               	orderItemForm = new Ext.FormPanel({
                    labelAlign: 'left',
                    labelWidth: 120, // label settings here cascade unless overridden
                    url: 'OrderServlet?action=14',
                    frame: true,
                    collapsible: true,
                    reader: new Ext.data.XmlReader({
                        record: 'item'
                    }, [{
                        name: 'id',
                        mapping: 'id'
                    }, {
                        name: 'photoName',
                        mapping: 'photoName'
                    },{
                        name: 'color',
                        mapping: 'color'
                    }, {
                        name: 'quantity',
                        mapping: 'quantity'
                    }, {
                        name: 'totalPrice',
                        mapping: 'totalPrice'
                    }, {
                        name: 'technicChartId',
                        mapping: 'technicChartId'
                    }, {
                        name: 'yarnId',
                        mapping: 'yarnId'
                    },{
                        name: 'unitPrice',
                        mapping: 'unitPrice'
                    }, {
                        name: 'coefficient',
                        mapping: 'coefficient'
                    },{
                        name: 'c1',
                        mapping: 'c1'
                    }, {
                        name: 'q1',
                        mapping: 'q1'
                    },{
                        name: 'c2',
                        mapping: 'c2'
                    }, {
                        name: 'q2',
                        mapping: 'q2'
                    },{
                        name: 'c3',
                        mapping: 'c3'
                    }, {
                        name: 'q3',
                        mapping: 'q3'
                    },{
                        name: 'c4',
                        mapping: 'c4'
                    }, {
                        name: 'q4',
                        mapping: 'q4'
                    },{
                        name: 'c5',
                        mapping: 'c5'
                    }, {
                        name: 'q5',
                        mapping: 'q5'
                    }]),
                    title: 'Edit order',
                    bodyStyle: 'padding:5px 5px 5px 5px;',
                    
                    
                    items: [{
                        id: 'orderId',
                        name: 'orderId',
                        xtype: 'hidden',
                        value: orderId
                    },{
						id: 'id',
						name: 'id',
						xtype: 'hidden'
					},{
						id: 'tcmId',
						name: 'tcmId',
						xtype: 'hidden'
					},{
                        id: 'q1',
                        name: 'q1',
                        xtype: 'hidden'
                    },{
						id: 'c1',
						name: 'c1',
						xtype: 'hidden'
					},{
                        id: 'q2',
                        name: 'q2',
                        xtype: 'hidden'
                    },{
						id: 'c2',
						name: 'c2',
						xtype: 'hidden'
					},{
                        id: 'q3',
                        name: 'q3',
                        xtype: 'hidden'
                    },{
						id: 'c3',
						name: 'c3',
						xtype: 'hidden'
					},{
                        id: 'q4',
                        name: 'q4',
                        xtype: 'hidden'
                    },{
						id: 'c4',
						name: 'c4',
						xtype: 'hidden'
					},{
                        id: 'q5',
                        name: 'q5',
                        xtype: 'hidden'
                    },{
						id: 'c5',
						name: 'c5',
						xtype: 'hidden'
					},{
						id: 'photoName',
						name: 'photoName',
						xtype: 'hidden'
					},{
                        xtype: 'fieldset',
                        collapsible: true,
                        title: 'Order item',
                        autoHeight: true,
                        items: [{
                            layout: 'column',
                            items: [{
                                columnWidth: .5,
                                layout: 'form',
                                items: [technicChartCombo,  {
                                    fieldLabel: 'Unit price&nbsp;&nbsp;<b>(€)</b>',
                                    width: '80%',
                                    name: 'unitPrice',
                                    id: 'unitPrice',
                                    readOnly: true,
									xtype: 'numberfield'
                                },{
                                    fieldLabel: 'Coefficient',
                                    width: '80%',
                                    name: 'coefficient',
                                    id: 'coefficient',
									xtype: 'numberfield',
									allowBlank: false,
                            		blankText: 'This fieled must be filled out.'
                                }]
                            }, {
                                columnWidth: .5,
                                layout: 'form',
                                items: [yarnCombo,{
                                    fieldLabel: 'Quantity',
                                    width: '80%',
                                    name: 'quantity',
                                    id: 'quantity',
                                    allowBlank: false,
                                    blankText: 'This fieled must be filled out.',
                                    xtype: 'numberfield',
                                    maxLength: 64,
                                    maxLengthText: 'The length of the text is too long to store.',
									onBlur: function(field){
										var coInput = document.getElementById('coefficient')
										quantity = this.getValue();
										if(c1 && q1 && quantity <= q1){
											coInput.value = c1;
											return;
										}
										if(q1 && c2 && q2 && quantity <= q2 && quantity > q1){
											coInput.value = c2;
											return;
										}
										if(q2 && c3 && q3 && quantity <= q3 && quantity > q2){
											coInput.value = c3;
											return;
										}
										if(q3 && c4 && q4 && quantity <= q4 && quantity > q3){
											coInput.value = c4;
											return;
										}
										if(q4 && c5 && q5 && quantity <= q5 && quantity > q4){
											coInput.value = c4;
											return;
										}
										coInput.value = 1;
									}
                                }, {
									fieldLabel: 'Color',
                                    width: '80%',
                                    name: 'color',
                                    id: 'color',
                                    xtype: 'textfield',
                                    maxLength: 64,
                                    maxLengthText: 'The length of the text is too long to store.'
								}]
                            }]
                        }, {
                            fieldLabel: '<img ext:qtip="(Unit price × coefficient × quantity" src="images/icons/information.png" style="float: left;">Cost&nbsp;&nbsp;<b>(€)</b>',
                            width: '80%',
                            name: 'totalPrice',
                            id: 'totalPrice',
                            allowBlank: false,
                            blankText: 'This fieled must be filled out.',
                            xtype: 'numberfield',
                            maxLength: 64,
                            maxLengthText: 'The length of the text is too long to store.'
                        }]
                    }],
                    
                    buttons: [{
                        text: 'Save',
                        handler: function(){
                            if (orderItemForm.getForm().isValid()) {
                                //technicChartId = technicChartCombo.getValue();
                                //yarnId = yarnCombo.getValue();
                                //document.getElementsByName('technicChartId')[0].value = technicChartCombo.getValue();
                                //document.getElementsByName('yarnId')[0].value = yarnCombo.getValue();
                                
                                orderItemForm.getForm().submit({
                                    method: 'post',
                                    success: function(form, action){
                                        //alert(form);
                                        messageTip.msg('Tip', 'Save successfully.');
                                        										
										 window.setTimeout(function(){
											window.location.reload();
										}, '700');
                                    },
                                    failure: function(form, action){
                                        //alert(form);
                                        messageTip.msg('Tip', 'Save unsuccessfully.');
                                        //orderForm.show();
                                    }
                                });
                            }
                        }
                    }, {
                        text: 'Reset',
                        handler: function(){
                            orderItemForm.getForm().reset();
                        }
                    }, {
                        text: 'Cancel',
                        handler: function(){
                              window.location = 'order_edit.html?id=' + orderId;
                        }
                    }]
                });
                orderItemForm.render('orderItem');
                
                orderItemForm.getForm().findField('totalPrice').on('focus', function(field){
                   if(document.getElementById('unitPrice').value && document.getElementById('coefficient').value && document.getElementById('quantity').value){
				   		document.getElementById('totalPrice').value = document.getElementById('unitPrice').value * document.getElementById('coefficient').value * document.getElementById('quantity').value
				   }else{
				   		orderItemForm.getForm().isValid();
				   }
                });
                
				var summary = new Ext.grid.GroupSummary(); 
				
                orderItemStore = new Ext.data.GroupingStore({
                
                    url: 'OrderServlet?action=15&id=' + orderId,
                    
                    reader: new Ext.data.XmlReader({
                    
                        record: 'item',
                        id: 'id',
                        totalRecords: 'itemTotal'
                    }, ['index', 'id', 'color', {
						name: 'quantity',
						type: 'int'
					}, {
						name: 'totalPrice',
						type: 'float'
					},{
						name: 'unitPrice',
						type: 'float'
					},{
						name: 'totalWeight',
						type: 'float'
					}, 'technicChart', 'yarn']),
                    
                    groupField: 'technicChart',
                    sortInfo: {
                        field: 'technicChart',
                        direction: "ASC"
                    }
                });
                
                orderItemGrid = new Ext.grid.GridPanel({
                    title: 'Order item list',
                    store: orderItemStore,
                    stripeRows: true,
                    height: 360,
                    columns: [{
                        id: 'technicChart',
                        header: 'Technic chart',
                        dataIndex: 'technicChart'
                    }, {
                        header: 'Yarn',
                        dataIndex: 'yarn',
						summaryType: 'count',
						summaryRenderer: function(v, params, data){
		                    return ((v === 0 || v > 1) ? '(' + v +' Order items)' : '(1 Order item)');
		                }
                    },{
						header: 'Unit price',
						dataIndex: 'unitPrice',
						align: 'right',
						renderer: eurMoney
					},{
                        header: 'Quantity',
                        dataIndex: 'quantity',
						align: 'right',
						summaryType:'sum'
                    },{
                        header: 'Cost',
						align: 'right',
                        dataIndex: 'totalPrice',
						groupable: false,
						renderer: eurMoney,
						summaryType:'sum'
                    }, {
                        header: 'Edit',
                        dataIndex: 'id',
                        width: 40,
                        renderer: renderEdit
                    }, {
                        header: 'Del',
                        dataIndex: 'id',
                        width: 40,
                        renderer: renderDelete
                    }],
                    
                    view: new Ext.grid.GroupingView({
                        forceFit: true,
						hideGroupedColumn: true,
                        groupTextTpl: '{text}({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
                    }),
                    loadMask: true,
					plugins: summary,
                    renderTo: 'orderItemList'
                });
                
                orderItemStore.load();
                
                function renderEdit(value, p, record){
                    return String.format('<a href="javascript: editItem(editCallback, {0});"><img src="images/icons/pencil.png" title="Edit" /></a>', record.id);
                }
                
                function renderDelete(value, p, record){
                    return String.format('<a href="javascript: deleteItem(deleteCallback, {0});"><img src="images/icons/delete.png" title="Delete"/></a>', record.id);
                }
            });
        </script>
    </head>
    <body>
        <div id="order">
        </div>
        <div id="orderItem" style="margin-top: 6px;">
        </div>
        <div id="orderItemList" style="margin-top: 6px;">
        </div>
    </body>
</html>
